package org.bdware.doip.endpoint.doipServer;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

public class DoipServerImpl implements DoipServer{
    static Logger logger = Logger.getLogger(DoipServerImpl.class);

    List<DoipListener> listeners;
    DoipServiceInfo serviceInfo;
//    RepositoryHandler handler;
    List<ListenerContainer> containers;
    DoipRequestHandler requestCallback;

    public DoipServerImpl(DoipServiceInfo info){
        this.serviceInfo = info;
        listeners = new ArrayList<>();
        for (DoipListenerInfo lsnrInfo:info.listenerInfos){
            DoipListener listener = DoipListenerGenerator.CreateDoipListener(lsnrInfo);
            listeners.add(listener);
        }
        containers = new ArrayList<>();
    }

    public static DoipServer createDoipServer(DoipServiceInfo info){
        DoipServerImpl server = new DoipServerImpl(info);
        return server;
    }

    @Override
    public void start(){
        logger.info("DOIPServiceInfo: " + serviceInfo.toJson());
        for(DoipListener listener:listeners){
            listener.setRequestHandler(requestCallback);
            ListenerContainer container = new ListenerContainer(listener);
            containers.add(container);
            container.start();
        }
    }

    @Override
    public void stop(){
        logger.info("Try to stop listeners:");
        for(DoipListener listener:listeners){
            listener.stop();
        }
        for(ListenerContainer c: containers){
            c.interrupt();
        }
    }

    @Override
    public void setRepositoryHandler(RepositoryHandler handler) {
        requestCallback = new RequestHandlerImpl(handler);
    }

    public class ListenerContainer extends Thread{
        DoipListener listener;
        ListenerContainer(DoipListener l){
            this.listener = l;
        }
        @Override
        public void run(){
            listener.start();
        }
    }

}
